﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using RoccaStore.Services;

namespace RoccaStore.Web.Controllers
{
    public class AddressBookController : Controller
    {
        private readonly IAddressBookService _addressBookService;
        private readonly IAccountService _accountService;

        public AddressBookController(
            IAddressBookService addressBookService,
            IAccountService accountService)
        {
            _addressBookService = addressBookService;
            _accountService = accountService;
        }

        public ActionResult Index()
        {
            return View();
        }

        [HttpGet]
        [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
        public JsonResult Search(string q)
        {
            if (_accountService.Current != null)
            {
                List<dynamic> emails = new List<dynamic>();
                List<Contact> addressBook = _addressBookService.GetBySearchTerm(q, _accountService.Current.ID);
                
                addressBook.ForEach(a => emails.Add(new { id = a.ID, name = a.Email }));

                return Json(emails, JsonRequestBehavior.AllowGet);
            }

            return Json(new { }, JsonRequestBehavior.AllowGet);
        }
    }
}
